/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc;

/**
 * <p>Project: RabbitMQ - ConsumerOne</p>
 * <p>Powered by yzc On 2023-12-19 17:18:22</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 */
public class ConsumerTwo {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置虚拟机的名称
        factory.setVirtualHost("/");
        //用户名
        factory.setUsername("admin");
        //密码
        factory.setPassword("5672");
        //设置端口好
        factory.setPort(5672);
        //设置mq服务器地址
        factory.setHost("127.0.0.1");

        //2.创建连接
        Connection conn = factory.newConnection();

        //3.创建信道
        Channel channel = conn.createChannel();

        //4.声明队列
        String queueName = "workQueue"; //队列名称
        /**
         * @Param queue 队列持久化
         * @Param durable 指队列是否持久化，如何未false，mq服务器停止或重启时，队列会丢失
         * @Param exclusive 是否是独占连接 如果设置为true，那么生产者和消费者必须是同一个连接对象
         * @Param autoDelete 是否是自动删除 如何队列没有消息 没有生产者或消费者关联队列，为true自动删除队列
         * @Param arguments 队列中的参数
         */
        channel.queueDeclare(queueName,true,false,false,null);
        System.out.println("消费者two:等待消费消息");
       //消息投递回调
        DeliverCallback deliverCallback=(consumerTag,message)->{
            System.out.println(consumerTag);
            //从mq中获得到的消息
            String msg = new String(message.getBody());
            //执行任务
            try {
                doTask(msg);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        };
        //5.消费消息
        channel.basicConsume(queueName,true,deliverCallback,consumerTag->{});

    }

    static void doTask(String msg) throws InterruptedException {
        System.out.println("消费者two开始执行任务:"+msg);
        for (int i = 0;i< msg.length();i++){
            Thread.sleep(1000);
            System.out.println("消费者two结束执行任务:"+msg);
        }
    }
}
